package com.sneakxy.cloudbase.platform.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sneakxy.cloudbase.platform.shiro.GetAuthorizationInfoRealm;

@Service
public class SecurityService implements ISecurityService {

	@Autowired
	private RealmSecurityManager realmSecurityManager;
	
	@Override
	public List<String> getPermissions() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		List<String> permissions = new ArrayList<>();
		realmSecurityManager.getRealms().forEach(realm -> {
			if(realm instanceof GetAuthorizationInfoRealm) {
				AuthorizationInfo info = ((GetAuthorizationInfoRealm) realm).getCurrentAuthorizationInfo(principals);
				permissions.addAll(info.getStringPermissions());
			}
		});
		return permissions;
	}

	@Override
	public List<String> getRoles() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		List<String> roles = new ArrayList<>();
		realmSecurityManager.getRealms().forEach(realm -> {
			if(realm instanceof GetAuthorizationInfoRealm) {
				AuthorizationInfo info = ((GetAuthorizationInfoRealm) realm).getCurrentAuthorizationInfo(principals);
				roles.addAll(info.getRoles());
			}
		});
		return roles;
	}

}
